package com.csii.modules.project.service.impl;

import com.csii.modules.project.service.dto.ProjectDTO;
import com.csii.modules.project.mapper.entity.ProjectUser;
import com.csii.modules.project.mapper.entity.Project;
import com.csii.modules.project.service.dto.ProjectUserDTO;
import com.csii.modules.project.mapper.ProjectUserMapper;
import com.csii.modules.project.mapper.ProjectMapper;
import com.csii.modules.project.service.IProjectService;
import com.csii.core.util.ConvertUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Collection;

/**
 * @Description: 项目
 * @Author: power-stdio
 * @Date:   2020-11-05
 * @Version: V1.0
 */
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements IProjectService {

	@Autowired
	private ProjectMapper projectMapper;
	@Autowired
	private ProjectUserMapper projectUserMapper;
	
	@Override
	@Transactional
	public void saveMain(ProjectDTO projectDTO, List<ProjectUserDTO> projectUserDTOList) {
		Project project = ConvertUtils.convert(Project.class,projectDTO);
		projectMapper.insert(project);
		if(projectUserDTOList!=null && projectUserDTOList.size()>0) {
		    List<ProjectUser> projectUserList = ConvertUtils.convertList(ProjectUser.class, projectUserDTOList);
			for(ProjectUser entity:projectUserList) {
				//外键设置
				entity.setProId(project.getId());
				projectUserMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void updateMain(ProjectDTO projectDTO,List<ProjectUserDTO> projectUserDTOList) {
		Project project = ConvertUtils.convert(Project.class,projectDTO);
		projectMapper.updateById(project);
		
		//1.先删除子表数据
		projectUserMapper.deleteByMainId(project.getId());
		
		//2.子表数据重新插入
		if(projectUserDTOList!=null && projectUserDTOList.size()>0) {
		    List<ProjectUser> projectUserList = ConvertUtils.convertList(ProjectUser.class, projectUserDTOList);
			for(ProjectUser entity:projectUserList) {
				//外键设置
				entity.setProId(project.getId());
				entity.setUpdateTime(new Date());
				projectUserMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void delMain(String id) {
		projectUserMapper.deleteByMainId(id);
		projectMapper.deleteById(id);
	}

	@Override
	@Transactional
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			projectUserMapper.deleteByMainId(id.toString());
			projectMapper.deleteById(id);
		}
	}

	@Override
	public List<ProjectDTO> queryList(String userName) {
		List<Project> list = projectMapper.queryList(userName);
		return ConvertUtils.convertList(ProjectDTO.class, list);
	}

}
